<template>
  <div class="batchManage">

    <div class="batch-search">
        <el-form :inline="true" @submit.native.prevent>
            <el-form-item label="批次号">
                <el-input size="small" v-model="searchInput" placeholder="请输入内容" @keyup.enter.native="handleSearch"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" size="mini" @click="handleSearch()">搜索</el-button>
            </el-form-item>
        </el-form>
    </div>

    <div class="table">
      <el-button type="primary" style="margin-bottom: 12px" @click="dialogAddExcel_show()">添加</el-button>
      <el-table border row-key="id" class="table" style="width: 100%;" border
        :data="tableList" v-loading="listLoading"  >

            <el-table-column prop="id" label="ID" width="100"></el-table-column>
            <el-table-column prop="number" label="批次号"width="130"></el-table-column>
            <el-table-column prop="_codeStr" label="状态"width="120"></el-table-column>
            <el-table-column prop="user.name" label="登记人" width="150"></el-table-column>
            <el-table-column prop="numCount" label="记录数" width="80"></el-table-column>
            <el-table-column prop="createDate" label="登记时间" width="160"></el-table-column>
            <el-table-column prop="description" label="描述"></el-table-column>
            <el-table-column label="操作" width="200">
              <template slot-scope="scope">
                <el-button @click="importFile(scope.row.id)" type="text" size="small"   v-if="scope.row.code==20">数据导入</el-button>
                <!--<el-button type="text" size="small" style="margin: 0 12px">日志</el-button>-->

                <el-button @click="showlogImportPolicy(scope.row)" type="text" size="small"   v-if="scope.row.code==-1">日志</el-button>

                <el-button @click="deleteImportPolicy(scope.row.id)" type="text" size="small">删除</el-button>
              </template>
            </el-table-column>
      </el-table>
      <div class="pagination">
            <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getTableData" />
      </div>
    </div>




    <el-dialog title="添加批次" :visible.sync="dialogAddExcel_Visible" width="30%">
      <el-form :model="dialogAddExcel_form" :rules="dialogAddExcel_rules" size="small">

        <el-form-item label="描述" :label-width="formLabelWidth">
            <el-input type="textarea" v-model="dialogAddExcel_form.description" :autosize="{ minRows: 4, maxRows: 6}"
                style="margin-top: 12px;"></el-input>
        </el-form-item>

        <el-form-item label="excel文件" :label-width="formLabelWidth">
            <el-upload  class="upload-demo"
              :action="url+'/policy/upload'"
              :http-request="uploadFile"
              :before-remove="beforeRemove"
              multiple   :limit="1"
              :file-list="dialogAddExcel_form.fileList"
              :auto-upload="false"
              ref="upload"
              accept=".xlsx">
                <el-button size="mini">选择文件</el-button>
                <div slot="tip" class="el-upload__tip">只能上传.xlsx文件</div>
            </el-upload>

            <div class="upload-text">
                <a target="_blank" href="/image/policy_template.xlsx"><img src="../../assets/upload/excel.jpg" alt=""></a>
                <div class="upload-warning">请按照模板文件上传数据，否则可能造成校验失败！</div>
            </div>

        </el-form-item>

       
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogAddExcel_Visible = false">取 消</el-button>
        <el-button type="primary" @click="dialog_handleSubmit">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import Pagination from "@/components/Pagination";
  import { importPolicyList, deleteImportPolicy } from '@/api/mark-policy';
  import { uploadFile, importFile } from "@/api/upload";


  export default {
    name: "batch-manage",
    components: { Pagination },
    data() {
      return {
        searchInput: '',
        listLoading: false,
        tableList : [],
        total: 0,
        listQuery: {
          page: 1,
          limit: 10
        },


        dialogAddExcel_Visible: false,
        formLabelWidth: '120px',
        dialogAddExcel_form: {
            description:'',
            fileList: [],
        },
        dialogAddExcel_rules: {
            description: [{ required: true, trigger: 'blur' }],
        },
        url: process.env.VUE_APP_BASE_API,
      }
    },
    computed: {},
    created() {
        console.log('[created]');
        this.getTableData();
    },
    methods: {
      getTableData() {
        console.log('[getTableData]');
        //this.listLoading = true;
        let param = {
          pageSize: this.listQuery.limit,
          pageNum: this.listQuery.page,
          number: this.searchInput,
        };
        importPolicyList(param).then(res => {
            // 预处理数据
            let codeHash = { '-1':'导入失败', 20:'未导入',100:'已导入'}              // code: 20-上传成功, 100-导入成功
            res.result.list.forEach((item) => {
                item._codeStr = codeHash[ item.code ];
                if(!item.numCount){ item.numCount=0; }
            });
            this.tableList = res.result.list;
            this.total = res.result.total;
            this.listLoading = false;
        });
      },
      handleSearch() {
        this.pageNum = 1;
        this.getTableData();
      },


      //////////////////// 上传及导入
      dialogAddExcel_show(){
          this.dialogAddExcel_form.fileList = [];
          this.dialogAddExcel_Visible = true
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${file.name}？`);
      },
      uploadFile(data) {
        console.log('[uploadFile]', data);

        this.loading = true;
        let formData = new FormData();

        formData.append('description', this.dialogAddExcel_form.description);
        formData.append('file', data.file);
        uploadFile(formData).then(res => {
            this.$message({ showClose: true, message: '添加成功', type: 'success' });
            this.dialogAddExcel_Visible = false;
            this.getTableData();
        }).catch(error => {
            this.$message({ type: 'error', message: '添加失败' });
        })
      },
      dialog_handleSubmit(){
            console.log('[dialog_handleSubmit]');
            // 表单验证
            if( !this.dialogAddExcel_form.description ){
                this.$message({ type: 'error', message: '请输入描述' });
                return false;
            }
            // 只能选择一个文件。 是通过<el-upload>的参数控制的: multiple   :limit="1"
            this.$refs.upload.submit();
      },
      // 导入已上传的excel
      importFile( excelId ) {
        this.$confirm("确定导入?", {type: "warning"}).then(() => {
            importFile({id: excelId}).then(res => {
                this.$message({ showClose: true, message: '导入成功', type: 'success' });
                this.getTableData();
            }).catch(error=>{
                this.$message({ type: 'error', message: '导入失败' });
            })
        }).catch(() => {})
      },
        // 删除导入记录, 并按导入的批次删除政策。
      deleteImportPolicy( excelId ){
        this.$confirm("删除时会将导入的政策也删除。确定删除?", {type: "warning"}).then(() => {
            deleteImportPolicy({id: excelId}).then(res => {
                this.$message({ showClose: true, message: '删除成功', type: 'success' });
                this.getTableData();
            }).catch(error=>{
                this.$message({ type: 'error', message: '删除失败' });
            })
        }).catch(() => {})
      },

      showlogImportPolicy( info ){
          let htm = info.msg.replace( /\|/gi, '<br>');
          this.$alert(htm, '', { confirmButtonText: '确定', dangerouslyUseHTMLString: true });
      },

    }
  }
</script>

<style lang="less" scoped>
  .batchManage {
    padding: 24px;

    .batch-search {
      width: 25%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin: 24px 0;

      .search-input {
        display: flex;
        align-items: center;
        flex: 1;
      }
    }


    .upload-text {
        display: flex;
        margin-top:20px;
        img {
          width: 50px;
          height: 50px;
          margin-right: 12px;
        }
        .upload-warning {
          color: red;
          width: 200px;
        }
    }



  }

</style>
